//
// Created by shen on 8/10/2024.
//

#ifndef TSAVPLAYER_OPENSLRENDER_H
#define TSAVPLAYER_OPENSLRENDER_H

#include <SLES/OpenSLES.h>
#include <SLES/OpenSLES_Android.h>
#include "AudioRender.h"
#include <queue>
#include "LogUtil.h"
#include <thread>

#define MAX_QUEUE_BUFFER_SIZE 3
class OpenSLRender : public AudioRender{
public:
    OpenSLRender();
    virtual ~OpenSLRender(){};
    virtual void Init();
    void ClearAudioCache() override;
    void RenderAudioFrame(uint8_t *pData, int dataSize) override;
    void UnInit() override;

private:
    int CreateEngine();
    int CreateOutputMixer();
    int CreateAudioPlayer();
    int GetAudioFrameQueueSize();
    void StartRender();
    void HandleAudioFrameQueue();
    static void CreateSLWaitingThread(OpenSLRender *openSlRender);
    static void AudioPlayerCallback(SLAndroidSimpleBufferQueueItf bufferQueue, void *context);


    SLObjectItf m_EngineObj = nullptr;
    SLEngineItf m_EngineEngine = nullptr;
    SLObjectItf m_OutputMixObj = nullptr;
    SLObjectItf m_AudioPlayerObj = nullptr;
    SLPlayItf m_AudioPlayerPlay = nullptr;
    SLVolumeItf m_AudioPlayerVolume = nullptr;
    SLAndroidSimpleBufferQueueItf m_BufferQueue;

    queue<AudioFrame *> m_AudioFrameQueue;

    thread *m_thread= nullptr;

    mutex m_Mutex;

    condition_variable m_Cond;

    volatile bool m_Exit = false;
};


#endif //TSAVPLAYER_OPENSLRENDER_H
